<template>
  <div class="paper-test-result">
    <!-- 结果概览 -->
    <el-card class="result-overview">
      <div class="overview-header">
        <div class="header-title">
          <h2>{{ paperInfo.name }}</h2>
          <div class="subtitle">测验结果分析</div>
        </div>
        <div class="header-buttons">
          <el-button @click="goToHome" icon="House">首页</el-button>
          <el-button type="primary" @click="goToPractice" icon="Refresh">重新练习</el-button>
        </div>
      </div>
      
      <!-- 成绩展示区 -->
      <div class="score-banner">
        <div class="score-main">
          <div class="score-circle">
            <el-progress 
              type="circle" 
              :percentage="scorePercentage" 
              :width="160"
              :stroke-width="12"
              :color="scoreColor"
              class="progress-element"
            />
            <div class="score-text">
              <span class="score">{{ userScore }}</span>
              <span class="total">/{{ totalScore }}</span>
            </div>
          </div>
          
          <div class="score-info">
            <!-- 计分方式说明 -->
            <div class="scoring-method-display">
              <div class="scoring-method-label">
                <el-icon><InfoFilled /></el-icon>
                <span>计分方式</span>
              </div>
              <div class="scoring-method-value">{{ scoringDescription || '系统默认计分' }}</div>
            </div>
            <div class="total-score-display">
              <div class="total-score-label">试卷总分</div>
              <div class="total-score-value">{{ totalScore }} 分</div>
            </div>
            <div class="user-score-display">
              <div class="user-score-label">您的得分</div>
              <div class="user-score-value" :style="{ color: scoreColor }">{{ userScore }} 分</div>
            </div>
            <div class="score-rate-display">
              <div class="score-rate-label">得分率</div>
              <div class="score-rate-value" :style="{ color: scoreColor }">{{ scorePercentage }}%</div>
            </div>
          </div>
        </div>
        
        <div class="score-details">
          <div class="detail-item">
            <div class="detail-icon">⏱️</div>
            <div class="detail-content">
              <span class="label">答题时间</span>
              <span class="value">{{ formatTime(timeSpent) }}</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-icon">📝</div>
            <div class="detail-content">
              <span class="label">题目总数</span>
              <span class="value">{{ totalQuestions }}题</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-icon">✅</div>
            <div class="detail-content">
              <span class="label">正确题数</span>
              <span class="value correct-value">{{ correctCount }}题</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-icon">❌</div>
            <div class="detail-content">
              <span class="label">错误题数</span>
              <span class="value wrong-value">{{ wrongCount }}题</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 详细得分信息 -->
      <div v-if="moduleScoreDetails.length > 0" class="detailed-score-section">
        <el-divider content-position="left">
          <span class="section-title expandable" @click="isDetailedScoreExpanded = !isDetailedScoreExpanded">
            <el-icon :class="{ 'rotate-icon': isDetailedScoreExpanded }">
              <ArrowRight />
            </el-icon>
            <span>各模块详细得分</span>
            <span class="expand-hint">（点击{{ isDetailedScoreExpanded ? '收起' : '展开' }}）</span>
          </span>
        </el-divider>
        
        <!-- 可折叠内容区域 -->
        <el-collapse-transition>
          <div v-show="isDetailedScoreExpanded" class="detailed-content">
            <!-- 总体统计卡片 -->
            <div class="overall-stats">
              <div class="stat-card total-score-stat">
                <div class="stat-icon">📊</div>
                <div class="stat-content">
                  <div class="stat-label">总得分</div>
                  <div class="stat-value">{{ userScore }}/{{ totalScore }}</div>
                </div>
              </div>
              <div class="stat-card accuracy-stat">
                <div class="stat-icon">🎯</div>
                <div class="stat-content">
                  <div class="stat-label">总正确率</div>
                  <div class="stat-value">{{ scorePercentage }}%</div>
                </div>
              </div>
              <div class="stat-card correct-stat">
                <div class="stat-icon">✅</div>
                <div class="stat-content">
                  <div class="stat-label">正确题数</div>
                  <div class="stat-value">{{ correctCount }}题</div>
                </div>
              </div>
              <div class="stat-card wrong-stat">
                <div class="stat-icon">❌</div>
                <div class="stat-content">
                  <div class="stat-label">错误题数</div>
                  <div class="stat-value">{{ wrongCount }}题</div>
                </div>
              </div>
            </div>
            
            <!-- 详细统计表格 -->
            <div class="table-wrapper">
              <el-table :data="moduleScoreDetails" border stripe style="width: 100%;">
                <el-table-column prop="moduleName" label="模块名称" min-width="180" />
                <el-table-column prop="total" label="题目总数" align="center" width="100" />
                <el-table-column prop="correct" label="正确题数" align="center" width="100">
                  <template #default="scope">
                    <span style="color: #67c23a; font-weight: bold;">{{ scope.row.correct }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="错误题数" align="center" width="100">
                  <template #default="scope">
                    <span style="color: #f56c6c; font-weight: bold;">{{ scope.row.total - scope.row.correct }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="scorePerQuestion" label="每题分值" align="center" width="100" />
                <el-table-column prop="score" label="得分" align="center" width="100">
                  <template #default="scope">
                    <span style="font-weight: bold; color: #409eff;">{{ scope.row.score }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="scoreRate" label="得分率" align="center" width="120">
                  <template #default="scope">
                    <el-progress 
                      :percentage="scope.row.scoreRate" 
                      :color="getProgressColor(scope.row.scoreRate)"
                      :stroke-width="8"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="评价" align="center" width="120">
                  <template #default="scope">
                    <el-tag :type="getScoreRateTagType(scope.row.scoreRate)" effect="dark">
                      {{ getPerformanceText(scope.row.scoreRate) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-collapse-transition>
      </div>
    </el-card>
    
    <!-- 主内容区 - 左侧题目区域，右侧答题卡 -->
    <div class="main-content">
      <!-- 题目区域 -->
      <el-card class="question-area">
        <template #header>
          <div class="question-header">
            <span>第{{ getCurrentQuestionContinuousNumber() }}题 (共{{ getSortedQuestions.length }}题)【{{ getCurrentQuestionModule() }}】</span>
          </div>
        </template>
        
        <!-- 题目内容 -->
        <div class="question-content" v-if="currentQuestion">
          <div class="question-main">
            <div class="question-title-container">
              <h3 class="question-title" v-html="sanitizeQuestionHtml(currentQuestion.content)"></h3>
            </div>
            
            <!-- 选项区域 -->
            <div class="options-container">
              <div class="options-area" v-if="currentQuestion.type === 'single' || currentQuestion.type === 'single_choice' || currentQuestion.type === 'multiple' || currentQuestion.type === 'multiple_choice'">
                <div 
                  v-for="(option, optIndex) in currentQuestion.options" 
                  :key="optIndex"
                  class="option-item"
                  :class="getOptionClass(currentQuestion, String.fromCharCode(65 + optIndex))"
                >
                  <span class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</span>
                  <span class="option-content" v-html="sanitizeOptionHtml(option.content)"></span>
                </div>
              </div>
              
              <!-- 判断题 -->
              <div class="true-false-area" v-else-if="currentQuestion.type === 'trueFalse' || currentQuestion.type === 'true_false'">
                <div 
                  class="option-item"
                  :class="getOptionClass(currentQuestion, 'true')"
                >
                  <span class="option-label">正确</span>
                </div>
                <div 
                  class="option-item"
                  :class="getOptionClass(currentQuestion, 'false')"
                >
                  <span class="option-label">错误</span>
                </div>
              </div>
              
              <!-- 填空题/简答题 -->
              <div class="text-answer-area" v-else-if="currentQuestion.type === 'fillBlank' || currentQuestion.type === 'fill_blank' || currentQuestion.type === 'shortAnswer' || currentQuestion.type === 'short_answer'">
                <div class="user-answer">
                  <span class="label">你的答案:</span>
                  <span>{{ userAnswers[`${currentQuestion.module}-${currentQuestion.id}`] || '未作答' }}</span>
                </div>
                <div class="correct-answer">
                  <span class="label">正确答案:</span>
                  <span class="correct-answer-content">{{ currentQuestion.correctAnswer }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 用户答案和正确答案 -->
          <div class="answer-section">
            <div class="answer-card">
              <div class="answer-item user-answer-item">
                <span class="answer-label">你的答案:</span>
                <span class="answer-value" v-if="currentQuestion.type === 'single' || currentQuestion.type === 'single_choice' || currentQuestion.type === 'trueFalse' || currentQuestion.type === 'true_false'">
                  {{ getAnswerText(currentQuestion, userAnswers[`${currentQuestion.module}-${currentQuestion.id}`]) }}
                </span>
                <span class="answer-value" v-else-if="currentQuestion.type === 'multiple' || currentQuestion.type === 'multiple_choice'">
                  {{ getMultipleAnswerText(userAnswers[`${currentQuestion.module}-${currentQuestion.id}`]) }}
                </span>
                <span class="answer-value" v-else>
                  {{ userAnswers[`${currentQuestion.module}-${currentQuestion.id}`] || '未作答' }}
                </span>
              </div>
              
              <div class="answer-divider"></div>
              
              <!-- 正确答案显示 -->
              <div class="answer-item correct-answer-item" v-if="currentQuestion.type === 'single' || currentQuestion.type === 'single_choice' || currentQuestion.type === 'trueFalse' || currentQuestion.type === 'true_false'">
                <span class="answer-label">正确答案:</span>
                <span class="answer-value">{{ getAnswerText(currentQuestion, currentQuestion.correctAnswer || '') }}</span>
              </div>
              
              <div class="answer-item correct-answer-item" v-else-if="currentQuestion.type === 'multiple' || currentQuestion.type === 'multiple_choice'">
                <span class="answer-label">正确答案:</span>
                <span class="answer-value">{{ getMultipleAnswerText(currentQuestion.correctAnswers || []) }}</span>
              </div>
              
              <div class="answer-item correct-answer-item" v-else-if="currentQuestion.type === 'fillBlank' || currentQuestion.type === 'fill_blank' || currentQuestion.type === 'shortAnswer' || currentQuestion.type === 'short_answer'">
                <span class="answer-label">正确答案:</span>
                <span class="answer-value">{{ currentQuestion.correctAnswer || '无' }}</span>
              </div>
            </div>
          </div>
          
          <!-- 题目解析 -->
          <div class="question-analysis-content" v-if="currentQuestion.analysis">
            <el-divider content-position="left">
              <span class="analysis-divider-text">
                <el-icon><Document /></el-icon>
                <span>题目解析</span>
              </span>
            </el-divider>
            <div class="analysis-wrapper">
              <div class="analysis-icon-badge">💡</div>
              <div class="analysis-text" v-html="sanitizeQuestionHtml(currentQuestion.analysis)"></div>
            </div>
          </div>
          
          <!-- 题目导航按钮 -->
          <div class="question-navigation-bottom">
            <div class="navigation-buttons">
              <el-button 
                :disabled="currentQuestionIndex === 0" 
                @click="previousQuestion"
                size="small"
              >
                上一题
              </el-button>
              <el-button 
                :disabled="currentQuestionIndex === getSortedQuestions.length - 1" 
                @click="nextQuestion"
                size="small"
                type="primary"
              >
                下一题
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 答题卡 -->
      <el-card class="answer-sheet">
        <template #header>
          <div class="sheet-header">
            <span class="sheet-title">
              <el-icon><Grid /></el-icon>
              <span>答题卡</span>
            </span>
            <div class="sheet-legend">
              <div class="legend-item">
                <span class="legend-dot correct"></span>
                <span class="legend-text">正确</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot wrong"></span>
                <span class="legend-text">错误</span>
              </div>
            </div>
          </div>
        </template>
        <div class="sheet-content">
          <!-- 按模块分组显示答题卡 -->
          <div 
            v-for="(moduleQuestions, module) in groupedQuestions" 
            :key="module"
            class="module-section"
          >
            <div class="module-name">
              <span class="module-name-text">{{ getModuleDisplayName(module) }}</span>
              <span class="module-count">{{ moduleQuestions.length }}题</span>
            </div>
            <div class="module-sheet">
              <div 
                v-for="(question, index) in moduleQuestions" 
                :key="`${module}-${question.id}`"
                class="sheet-item"
                :class="getQuestionStatusClass(question)"
                @click="jumpToQuestion(module, index)"
              >
                <span class="sheet-item-number">{{ getContinuousQuestionNumber(module, index) }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import * as paperApi from '@/api/paper'
import * as paperResultApi from '@/api/paperResult'
import * as paperScoreApi from '@/api/paperScore' // 添加试卷分值API导入
import { modifyQuestionContentImageSizeInHTML, modifyOptionImageSizeInHTML } from '@/utils/htmlUtils'

// 定义题目数据类型
interface Question {
  id: number
  type: string // single, multiple, trueFalse, fillBlank, shortAnswer
  content: string
  options?: { content: string }[]
  correctAnswer?: string
  correctAnswers?: string[]
  analysis?: string
  module?: string // 添加模块字段
  category?: string // 添加分类字段，用于判断推理的细分分类
}

// 定义试卷信息类型
interface PaperInfo {
  id: number
  name: string
  totalDuration: number
  totalQuestions: number
}

// 定义用户答案类型
interface UserAnswer {
  [questionId: number]: any;
  [questionKey: string]: any; // 支持模块-题目ID格式的键
}

// 路由
const route = useRoute()
const router = useRouter()

// 用户存储
const userStore = useUserStore()

// 试卷信息
const paperInfo = ref<PaperInfo>({
  id: 0,
  name: '试卷名称',
  totalDuration: 120,
  totalQuestions: 100
})

// 试卷题目
const paperQuestions = ref<Question[]>([])

// 用户答案
const userAnswers = ref<UserAnswer>({})

// 用户得分
const userScore = ref(0)
const totalScore = ref(0) // 修改默认值为0，避免在没有数据时显示错误的百分比

// 试卷分值信息
const paperScoreInfo = ref<any>(null)

// 计分方式说明
const scoringDescription = ref<string>('')

// 详细得分展开状态
const isDetailedScoreExpanded = ref(false)

// 统计信息（用于显示）
const calculatedCorrectCount = ref(0)
const calculatedWrongCount = ref(0)

// 模块得分详情（用于显示）
const moduleScoreDetails = ref<Array<{
  moduleName: string;
  correct: number;
  total: number;
  scorePerQuestion: number;
  score: number;
  scoreRate: number;
  scoreClass: string;
}>>([])

// 答题时间
const timeSpent = ref(0) // 秒

// 分析过滤器
const analysisFilter = ref('all')

// 当前题目索引
const currentQuestionIndex = ref(0)

// 当前题目
const currentQuestion = computed(() => {
  return getSortedQuestions.value[currentQuestionIndex.value]
})

// 获取按模块排序的题目数组
const getSortedQuestions = computed(() => {
  const sortedQuestions: Question[] = [];
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  
  // 按照模块顺序添加题目
  moduleOrder.forEach(module => {
    if (groupedQuestions.value[module]) {
      sortedQuestions.push(...groupedQuestions.value[module]);
    }
  });
  
  // 添加其他未在顺序列表中的模块
  Object.keys(groupedQuestions.value).forEach(module => {
    if (!moduleOrder.includes(module)) {
      sortedQuestions.push(...groupedQuestions.value[module]);
    }
  });
  
  return sortedQuestions;
});

// 按模块分组的题目
const groupedQuestions = computed(() => {
  const groups: Record<string, Question[]> = {};
  
  paperQuestions.value.forEach(question => {
    const module = question.module || 'unknown';
    if (!groups[module]) {
      groups[module] = [];
    }
    groups[module].push(question);
  });
  
  // 定义模块顺序: 政治理论、常识、言语、数量关系、判断、资料
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  
  // 按照指定顺序重新组织对象
  const orderedGroups: Record<string, Question[]> = {};
  
  // 先按指定顺序添加模块
  moduleOrder.forEach(module => {
    if (groups[module]) {
      orderedGroups[module] = groups[module];
    }
  });
  
  // 添加其他未在顺序列表中的模块
  Object.keys(groups).forEach(module => {
    if (!moduleOrder.includes(module)) {
      orderedGroups[module] = groups[module];
    }
  });
  
  return orderedGroups;
});

// 获取试卷分值信息
const fetchPaperScoreInfo = async (paperId: number) => {
  try {
    // 只从sessionStorage获取试卷分值信息，不再自动从后端获取
    const paperScoreData = sessionStorage.getItem(`paperScore_${paperId}`)
    if (paperScoreData) {
      const paperScoreRelation = JSON.parse(paperScoreData)
      if (paperScoreRelation.paperScoreInfo) {
        paperScoreInfo.value = paperScoreRelation.paperScoreInfo
        console.log('从sessionStorage获取试卷分值信息:', paperScoreInfo.value)
        return true
      }
    }
    
    // 如果sessionStorage中没有，说明用户没有选择试卷分值配置
    console.log('未找到试卷分值配置，将使用后端返回的得分数据')
    return false
  } catch (error) {
    console.error('获取试卷分值信息失败:', error)
    return false
  }
}

// 根据试卷分值信息计算得分
const calculateScoreByPaperScoreInfo = () => {
  if (!paperScoreInfo.value || !paperScoreInfo.value.details) {
    console.warn('没有试卷分值信息，无法计算得分');
    return { score: 0, correctCount: 0, wrongCount: 0 };
  }
  
  console.log('=== 开始计算试卷得分 ===');
  console.log('试卷分值配置:', paperScoreInfo.value);
  
  let totalPoints = 0;
  let correctCount = 0;
  let wrongCount = 0;
  
  // 模块名称中英文映射
  const moduleNameMap: Record<string, string> = {
    'politics': '政治理论',
    'commonSense': '常识判断',
    'language': '言语理解与表达',
    'quantity': '数量关系',
    'judgment': '判断推理',
    'dataAnalysis': '资料分析'
  };
  
  // 判断推理分类的中英文映射
  const judgmentCategoryMap: Record<string, string> = {
    '图形推理': 'graphicReasoning',
    '定义判断': 'definitionJudgment',
    '类比推理': 'analogicalReasoning',
    '逻辑判断': 'logicalJudgment'
  };
  
  // 创建模块分值映射
  const moduleScoreMap: Record<string, { correct: number; total: number; scorePerQuestion: number }> = {};
  
  // 初始化各模块得分信息
  paperScoreInfo.value.details.forEach((detail: any) => {
    const moduleKey = detail.module || '';
    console.log('处理分值明细:', detail);
    
    // 将中文模块名映射为英文模块名
    let englishModuleKey = '';
    
    // 检查是否是判断推理的分类
    if (judgmentCategoryMap[moduleKey]) {
      // 判断推理的分类统一归到judgment模块下，使用中文名称作为子分类
      englishModuleKey = `judgment-${moduleKey}`;
    } else {
      // 其他模块，查找对应的英文名称
      const foundKey = Object.keys(moduleNameMap).find(key => moduleNameMap[key] === moduleKey);
      englishModuleKey = foundKey || moduleKey;
    }
    
    moduleScoreMap[englishModuleKey] = {
      correct: 0,
      total: detail.questionCount || 0,
      scorePerQuestion: detail.scorePerQuestion || 0
    };
    console.log(`初始化模块 ${englishModuleKey} (${moduleKey}):`, moduleScoreMap[englishModuleKey]);
  });
  
  console.log('模块分值映射:', moduleScoreMap);
  console.log('用户答案总数:', Object.keys(userAnswers.value).length);
  console.log('试卷题目总数:', paperQuestions.value.length);
  
  // 统计各模块正确题数
  Object.keys(userAnswers.value).forEach(key => {
    const [module, idStr] = key.split('-');
    const questionId = Number(idStr);
    const question = paperQuestions.value.find(q => q.id === questionId && q.module === module);
    
    if (!question) {
      console.warn(`未找到题目: module=${module}, id=${questionId}`);
      return;
    }
    
    const userAnswer = userAnswers.value[key];
    if (!userAnswer) {
      console.log(`题目 ${key} 未作答`);
      return;
    }
    
    let isCorrect = false;
    
    // 根据题目类型判断答案是否正确
    if (question.type === 'single' || question.type === 'single_choice' || 
        question.type === 'trueFalse' || question.type === 'true_false') {
      isCorrect = userAnswer === question.correctAnswer;
      console.log(`题目 ${key} [${question.type}] - 用户答案: ${userAnswer}, 正确答案: ${question.correctAnswer}, 是否正确: ${isCorrect}`);
    } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
      const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : [];
      const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : [];
      isCorrect = JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort());
      console.log(`题目 ${key} [${question.type}] - 用户答案: ${JSON.stringify(userAnswersArray)}, 正确答案: ${JSON.stringify(correctAnswersArray)}, 是否正确: ${isCorrect}`);
    }
    
    if (isCorrect) {
      correctCount++;
      
      // 判断推理模块需要根据分类累加得分
      if (module === 'judgment' && question.category) {
        const categoryKey = `judgment-${question.category}`;
        console.log(`判断推理题目 ${key} 的分类: ${question.category}, categoryKey: ${categoryKey}`);
        if (moduleScoreMap[categoryKey]) {
          moduleScoreMap[categoryKey].correct++;
          console.log(`${categoryKey} 正确题数 +1, 当前: ${moduleScoreMap[categoryKey].correct}`);
        } else {
          console.warn(`未找到判断推理分类映射: ${categoryKey}, 可用的映射:`, Object.keys(moduleScoreMap));
        }
      } else {
        // 其他模块正常累加
        if (moduleScoreMap[module]) {
          moduleScoreMap[module].correct++;
          console.log(`${module} 正确题数 +1, 当前: ${moduleScoreMap[module].correct}`);
        } else {
          console.warn(`未找到模块映射: ${module}, 可用的映射:`, Object.keys(moduleScoreMap));
        }
      }
    } else {
      wrongCount++;
    }
  });
  
  console.log('=== 统计完成，开始计算得分 ===');
  
  // 清空之前的详细得分信息
  const detailsList: Array<{
    moduleName: string;
    correct: number;
    total: number;
    scorePerQuestion: number;
    score: number;
    scoreRate: number;
    scoreClass: string;
  }> = [];
  
  // 模块名称映射
  const moduleDisplayNames: Record<string, string> = {
    'politics': '政治理论',
    'commonSense': '常识判断',
    'language': '言语理解与表达',
    'quantity': '数量关系',
    'dataAnalysis': '资料分析',
    'judgment-图形推理': '判断推理-图形推理',
    'judgment-定义判断': '判断推理-定义判断',
    'judgment-类比推理': '判断推理-类比推理',
    'judgment-逻辑判断': '判断推理-逻辑判断'
  };
  
  // 计算总得分并生成详细信息
  Object.keys(moduleScoreMap).forEach(moduleKey => {
    const moduleInfo = moduleScoreMap[moduleKey];
    const moduleScore = moduleInfo.correct * moduleInfo.scorePerQuestion;
    totalPoints += moduleScore;
    
    // 计算得分率
    const scoreRate = moduleInfo.total > 0 
      ? Math.round((moduleInfo.correct / moduleInfo.total) * 100) 
      : 0;
    
    // 根据得分率确定样式
    let scoreClass = '';
    if (scoreRate >= 80) scoreClass = 'score-excellent';
    else if (scoreRate >= 60) scoreClass = 'score-good';
    else scoreClass = 'score-poor';
    
    // 添加到详细列表
    detailsList.push({
      moduleName: moduleDisplayNames[moduleKey] || moduleKey,
      correct: moduleInfo.correct,
      total: moduleInfo.total,
      scorePerQuestion: moduleInfo.scorePerQuestion,
      score: Math.round(moduleScore * 10) / 10,
      scoreRate,
      scoreClass
    });
    
    console.log(`${moduleKey} 得分:`, moduleScore, `正确题数: ${moduleInfo.correct}/${moduleInfo.total}, 每题分值: ${moduleInfo.scorePerQuestion}`);
  });
  
  // 更新模块得分详情
  moduleScoreDetails.value = detailsList;
  
  console.log('=== 计算总得分:', totalPoints, '===');
  console.log('正确题数:', correctCount, '错误题数:', wrongCount);
  
  return {
    score: Math.round(totalPoints * 10) / 10, // 保留一位小数
    correctCount,
    wrongCount
  };
};

// 获取试卷结果数据
const fetchPaperResult = async () => {
  try {
    // 从路由参数获取试卷ID
    const paperId = route.query.paperId as string
    
    // 检查试卷ID是否存在
    if (!paperId) {
      ElMessage.error('试卷ID不存在')
      router.back()
      return
    }
    
    // 获取试卷信息
    const paperRes: any = await paperApi.getPaperById(Number(paperId))
    if (paperRes.code === 200) {
      paperInfo.value = paperRes.data
    } else {
      ElMessage.error('获取试卷信息失败: ' + (paperRes.message || '未知错误'))
      router.back()
      return
    }
    
    // 获取试卷题目
    const questionsRes: any = await paperApi.getPaperQuestions(Number(paperId))
    if (questionsRes.code === 200) {
      // 根据实际返回的数据结构处理题目
      // 后端返回的数据结构是按模块分类的，需要合并成一个数组
      const allQuestions: any[] = [];
      if (questionsRes.data) {
        // 定义模块顺序，与PaperTestPractice.vue保持一致
        const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
        
        // 按照模块顺序添加题目
        moduleOrder.forEach(module => {
          if (questionsRes.data[module] && Array.isArray(questionsRes.data[module])) {
            questionsRes.data[module].forEach((question: any) => {
              // 处理选项数据，确保是对象数组格式
              let options = question.options;
              if (typeof question.options === 'string') {
                try {
                  options = JSON.parse(question.options);
                } catch (e) {
                  // 如果解析失败，保持原样
                  options = question.options;
                }
              }
              
              // 如果options是数组，确保每个选项是对象格式
              if (Array.isArray(options)) {
                options = options.map(option => {
                  if (typeof option === 'string') {
                    return { content: option };
                  }
                  return option;
                });
              } 
              // 如果options是对象，转换为数组格式
              else if (typeof options === 'object' && options !== null) {
                const optionsArray = [];
                for (const key in options) {
                  if (options.hasOwnProperty(key)) {
                    optionsArray.push({ content: options[key] });
                  }
                }
                options = optionsArray;
              }
              
              // 确保题目对象有正确的type字段（使用模块名称作为type字段值）
              // 同时保留原始的questionType字段用于选项显示判断
              allQuestions.push({
                ...question,
                type: question.questionType || question.type || module, // 使用questionType或type字段或模块名称
                options: options,
                module: module // 保存模块信息用于排序
              });
            });
          }
        });
        
        // 添加其他未在顺序列表中的模块
        Object.keys(questionsRes.data).forEach(module => {
          if (!moduleOrder.includes(module) && Array.isArray(questionsRes.data[module])) {
            questionsRes.data[module].forEach((question: any) => {
              // 处理选项数据，确保是对象数组格式
              let options = question.options;
              if (typeof question.options === 'string') {
                try {
                  options = JSON.parse(question.options);
                } catch (e) {
                  // 如果解析失败，保持原样
                  options = question.options;
                }
              }
              
              // 如果options是数组，确保每个选项是对象格式
              if (Array.isArray(options)) {
                options = options.map(option => {
                  if (typeof option === 'string') {
                    return { content: option };
                  }
                  return option;
                });
              } 
              // 如果options是对象，转换为数组格式
              else if (typeof options === 'object' && options !== null) {
                const optionsArray = [];
                for (const key in options) {
                  if (options.hasOwnProperty(key)) {
                    optionsArray.push({ content: options[key] });
                  }
                }
                options = optionsArray;
              }
              
              // 确保题目对象有正确的type字段（使用模块名称作为type字段值）
              // 同时保留原始的questionType字段用于选项显示判断
              allQuestions.push({
                ...question,
                type: question.questionType || question.type || module, // 使用questionType或type字段或模块名称
                options: options,
                module: module // 保存模块信息用于排序
              });
            });
          }
        });
      }
      
      paperQuestions.value = allQuestions;
      // 开发环境下输出调试信息
      if (import.meta.env.DEV) {
        console.log('处理后的题目数据:', allQuestions);
      }
    } else {
      ElMessage.error('获取试卷题目失败: ' + (questionsRes.message || '未知错误'))
      router.back()
      return
    }
    
    // 上一题
    const previousQuestion = () => {
      if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
      }
    }
    
    // 下一题
    const nextQuestion = () => {
      if (currentQuestionIndex.value < getSortedQuestions.value.length - 1) {
        currentQuestionIndex.value++
      }
    }
    
    // 跳转到指定题目
    const jumpToQuestion = (module: string, indexInModule: number) => {
      // 直接根据模块和模块内索引计算在排序后数组中的位置
      const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
      let totalCount = 0;
      
      // 找到目标模块在顺序中的位置
      const targetModuleIndex = moduleOrder.indexOf(module);
      
      // 如果目标模块不在标准模块顺序中，则在其他模块中查找
      if (targetModuleIndex === -1) {
        // 计算标准模块的总题目数
        for (let i = 0; i < moduleOrder.length; i++) {
          if (groupedQuestions.value[moduleOrder[i]]) {
            totalCount += groupedQuestions.value[moduleOrder[i]].length;
          }
        }
        // 在其他模块中查找目标模块
        const otherModules = Object.keys(groupedQuestions.value).filter(m => !moduleOrder.includes(m));
        const targetOtherModuleIndex = otherModules.indexOf(module);
        if (targetOtherModuleIndex !== -1) {
          for (let i = 0; i < targetOtherModuleIndex; i++) {
            totalCount += groupedQuestions.value[otherModules[i]].length;
          }
        }
      } else {
        // 计算目标模块之前所有模块的题目数量
        for (let i = 0; i < targetModuleIndex; i++) {
          const prevModule = moduleOrder[i];
          if (groupedQuestions.value[prevModule]) {
            totalCount += groupedQuestions.value[prevModule].length;
          }
        }
      }
      
      // 计算最终索引：之前模块的题目总数 + 当前模块内的索引
      const index = totalCount + indexInModule;
      if (index >= 0 && index < getSortedQuestions.value.length) {
        currentQuestionIndex.value = index;
      }
    }
    
    // 获取当前题目的连续编号
    const getCurrentQuestionContinuousNumber = () => {
      if (!currentQuestion.value) return 0;
      
      // 找到当前题目所在的模块
      const currentModule = currentQuestion.value.module;
      if (!currentModule) return currentQuestionIndex.value + 1;
      
      // 找到当前题目在模块中的索引
      const moduleQuestions = groupedQuestions.value[currentModule];
      if (!moduleQuestions) return currentQuestionIndex.value + 1;
      
      const indexInModule = moduleQuestions.findIndex(q => q.id === currentQuestion.value.id);
      if (indexInModule === -1) return currentQuestionIndex.value + 1;
      
      // 使用已有的函数计算连续编号
      return getContinuousQuestionNumber(currentModule, indexInModule);
    };
    
    // 获取连续的题目编号
    const getContinuousQuestionNumber = (module: string, indexInModule: number) => {
      // 计算当前模块之前所有模块的题目总数
      const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
      let totalCount = 0;
      
      // 找到当前模块在顺序中的位置
      const currentModuleIndex = moduleOrder.indexOf(module);
      
      // 计算之前所有模块的题目数量
      for (let i = 0; i < currentModuleIndex; i++) {
        const prevModule = moduleOrder[i];
        if (groupedQuestions.value[prevModule]) {
          totalCount += groupedQuestions.value[prevModule].length;
        }
      }
      
      // 加上当前模块内的索引+1（因为索引从0开始）
      return totalCount + indexInModule + 1;
    };
    
    // 获取模块显示名称
    const getModuleDisplayName = (module: string) => {
      const moduleMap: Record<string, string> = {
        'politics': '政治理论',
        'commonSense': '常识判断',
        'language': '言语理解与表达',
        'quantity': '数量关系',
        'judgment': '判断推理',
        'dataAnalysis': '资料分析'
      };
      
      return moduleMap[module] || module;
    };
    
    // 获取当前题目模块
    const getCurrentQuestionModule = () => {
      if (!currentQuestion.value || !currentQuestion.value.module) return ''
      
      return getModuleDisplayName(currentQuestion.value.module);
    }
    
    // 获取试卷分值信息
    await fetchPaperScoreInfo(Number(paperId))
    
    // 获取用户的测验结果
    // 使用Pinia存储中的用户ID
    // 修复：检查 userId 字段而不是 id 字段
    if (userStore.userInfo && userStore.userInfo.userId) {
      // 修复：使用 userId 字段而不是 id 字段
      const userId = userStore.userInfo.userId;
      const resultsRes: any = await paperResultApi.getPaperResultsByUserIdAndPaperId(userId, Number(paperId))
      if (resultsRes.code === 200 && resultsRes.data && resultsRes.data.length > 0) {
        // 获取最新的测验结果
        const latestResult = resultsRes.data[0]; // 假设后端已经按时间倒序排列
        
        // 设置用户答案
        if (latestResult.userAnswers) {
          userAnswers.value = latestResult.userAnswers;
          // 开发环境下输出调试信息
          if (import.meta.env.DEV) {
            console.log('用户答案:', latestResult.userAnswers);
          }
          
          // 同时也支持模块-题目ID格式的键，确保与PaperTestPractice.vue兼容
          // 先直接赋值原始数据，然后转换为模块-ID格式
          Object.keys(latestResult.userAnswers).forEach(key => {
            // 如果键已经是模块-题目ID格式，直接使用
            if (/^[^-]+-\d+$/.test(key)) {
              userAnswers.value[key] = latestResult.userAnswers[key];
            }
            // 如果键是数字格式，需要转换为模块-ID格式
            else if (/^\d+$/.test(key)) {
              const questionId = Number(key);
              const answer = latestResult.userAnswers[key];
              
              // 查找当前题目属于哪个模块，只为对应模块设置答案
              const targetQuestion = paperQuestions.value.find(q => q.id === questionId);
              if (targetQuestion && targetQuestion.module) {
                // 只为找到的题目所在模块设置答案，避免跨模块污染
                userAnswers.value[`${targetQuestion.module}-${questionId}`] = answer;
              }
            }
          });
          
          // 开发环境下输出调试信息
          if (import.meta.env.DEV) {
            console.log('处理后的用户答案:', userAnswers.value);
            console.log('试卷题目信息:', paperQuestions.value.map(q => ({ id: q.id, module: q.module })));
          }
        }
        
        // 设置用户得分信息 - 使用试卷分值重新计算得分
        console.log('=== 准备计算得分 ===')
        console.log('paperScoreInfo.value:', paperScoreInfo.value)
        console.log('paperScoreInfo.value.details:', paperScoreInfo.value?.details)
                
        if (paperScoreInfo.value && paperScoreInfo.value.details) {
          console.log('使用试卷分值信息重新计算得分')
          // 使用试卷分值信息重新计算得分
          const calculatedScore = calculateScoreByPaperScoreInfo()
          console.log('计算结果:', calculatedScore)
                  
          // 更新得分和统计信息
          userScore.value = calculatedScore.score
          totalScore.value = paperScoreInfo.value.totalScore || 100
          calculatedCorrectCount.value = calculatedScore.correctCount
          calculatedWrongCount.value = calculatedScore.wrongCount
          
          // 设置计分方式说明
          scoringDescription.value = `${paperScoreInfo.value.examName} - ${paperScoreInfo.value.subject} (总分${paperScoreInfo.value.totalScore}分)`
                  
          console.log('最终得分:', userScore.value, '总分:', totalScore.value)
          console.log('正确题数:', calculatedCorrectCount.value, '错误题数:', calculatedWrongCount.value)
        } else {
          console.log('没有试卷分值信息，使用数据库中的得分')
          // 如果没有试卷分值信息，使用数据库中的得分
          userScore.value = latestResult.score || 0
          totalScore.value = latestResult.totalScore || 0
          
          // 设置计分方式说明
          scoringDescription.value = latestResult.scoringDescription || '系统默认计分(每题1分)'
          
          console.log('数据库得分:', userScore.value, '总分:', totalScore.value)
        }
        console.log('=== 准备计算得分 ===');
        console.log('paperScoreInfo.value:', paperScoreInfo.value);
        console.log('paperScoreInfo.value.details:', paperScoreInfo.value?.details);
                
        if (paperScoreInfo.value && paperScoreInfo.value.details) {
          console.log('使用试卷分值信息重新计算得分');
          // 使用试卷分值信息重新计算得分
          const calculatedScore = calculateScoreByPaperScoreInfo();
          console.log('计算结果:', calculatedScore);
                  
          // 更新得分和统计信息
          userScore.value = calculatedScore.score;
          totalScore.value = paperScoreInfo.value.totalScore || 100;
          calculatedCorrectCount.value = calculatedScore.correctCount;
          calculatedWrongCount.value = calculatedScore.wrongCount;
                  
          console.log('最终得分:', userScore.value, '总分:', totalScore.value);
          console.log('正确题数:', calculatedCorrectCount.value, '错误题数:', calculatedWrongCount.value);
        } else {
          console.log('没有试卷分值信息，使用数据库中的得分');
          // 如果没有试卷分值信息，使用数据库中的得分
          userScore.value = latestResult.score || 0;
          totalScore.value = latestResult.totalScore || 0;
          console.log('数据库得分:', userScore.value, '总分:', totalScore.value);
        }
        timeSpent.value = latestResult.timeSpent || 0;
        
        // 检查是否是从交卷页面跳转过来的，如果是则显示整合的提示信息
        if (route.query.submitSuccess === 'true') {
          ElMessage.success('试卷提交成功，结果加载成功');
        } else {
          ElMessage.success('结果加载成功');
        }
      } else {
        // 检查是否是从交卷页面跳转过来的，如果是则显示整合的提示信息
        if (route.query.submitSuccess === 'true') {
          ElMessage.success('试卷提交成功，正在加载结果...');
        } else {
          ElMessage.warning('未找到测验结果数据，可能是因为刚刚提交的试卷还在处理中');
        }
      }
    } else {
      ElMessage.error('用户未登录或用户信息不完整')
    }
  } catch (error: any) {
    console.error('结果加载失败:', error);
    // 检查是否是从交卷页面跳转过来的，如果是则显示整合的提示信息
    if (route.query.submitSuccess === 'true') {
      ElMessage.error('试卷提交成功，但结果加载失败: ' + (error.message || '未知错误'));
    } else {
      ElMessage.error('结果加载失败: ' + (error.message || '未知错误'));
    }
  }
}

// 获取题目类型文本
const getQuestionTypeText = (type: string) => {
  // 如果type为空或未定义，返回默认值
  if (!type) return '未知题型';
  
  // 直接匹配中文题型
  if (['单选题', '多选题', '判断题', '填空题', '简答题'].includes(type)) {
    return type;
  }
  
  // 英文题型映射
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    trueFalse: '判断题',
    fillBlank: '填空题',
    shortAnswer: '简答题',
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    short_answer: '简答题'
  };
  
  // 返回映射值或原值
  return typeMap[type] || type;
};

// 获取题目状态类
const getQuestionStatusClass = (question: Question) => {
  // 从用户答案中获取当前题目的答案，使用模块+ID作为键
  const userAnswer = userAnswers.value[`${question.module}-${question.id}`];
  if (!userAnswer) return 'unanswered';
  
  if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
    return userAnswer === question.correctAnswer ? 'correct' : 'wrong';
  } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
    const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : [];
    const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : [];
    return JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort()) ? 'correct' : 'wrong';
  }
  return 'unanswered';
}

// 获取题目状态文本
const getQuestionStatusText = (question: Question) => {
  // 使用模块+ID作为键获取用户答案
  const userAnswer = userAnswers.value[`${question.module}-${question.id}`]
  if (!userAnswer) return '未答'
  
  if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
    return userAnswer === question.correctAnswer ? '正确' : '错误'
  } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
    const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : []
    const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : []
    return JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort()) ? '正确' : '错误'
  }
  return '未答'
}

// 判断选项是否正确
const isCorrectOption = (question: Question, option: string) => {
  // 开发环境下输出调试信息
  if (import.meta.env.DEV) {
    console.log('检查正确选项:', { questionType: question.type, option, correctAnswer: question.correctAnswer, correctAnswers: question.correctAnswers });
  }
  
  if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
    return option === question.correctAnswer
  } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
    return question.correctAnswers?.includes(option) || false
  }
  return false
}

// 获取选项类
const getOptionClass = (question: Question, option: string) => {
  // 使用模块+ID作为键获取用户答案
  const userAnswer = userAnswers.value[`${question.module}-${question.id}`]
  const classes = []
  
  // 正确答案标记
  if (isCorrectOption(question, option)) {
    classes.push('correct-option')
  }
  
  // 用户选择标记
  if (userAnswer) {
    if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
      if (userAnswer === option) {
        classes.push('user-selected')
        if (userAnswer !== question.correctAnswer) {
          classes.push('user-wrong')
        }
      }
    } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
      if (Array.isArray(userAnswer) && userAnswer.includes(option)) {
        classes.push('user-selected')
        if (!question.correctAnswers?.includes(option)) {
          classes.push('user-wrong')
        }
      }
    }
  }
  
  return classes
}

// 获取答案文本
const getAnswerText = (question: Question, answer: string) => {
  if (!answer) return '未作答'
  if ((question.type === 'single' || question.type === 'single_choice') && question.options) {
    // 只返回选项字母，不返回选项内容
    return answer
  }
  if (question.type === 'trueFalse' || question.type === 'true_false') {
    return answer === 'true' ? '正确' : '错误'
  }
  return answer
}

// 获取多选答案文本
const getMultipleAnswerText = (answers: string[] | undefined) => {
  if (!answers || answers.length === 0) return '未作答'
  // 只返回选项字母，不返回选项内容
  return answers.join(', ')
}

// 格式化时间
const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}分${secs}秒`
}

// 重新练习
const goToPractice = () => {
  router.push({
    path: '/paper-test/practice',
    query: {
      paperId: paperInfo.value.id.toString()
    }
  })
}

// 添加返回首页的方法
const goToHome = () => {
  router.push('/');
};

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < getSortedQuestions.value.length - 1) {
    currentQuestionIndex.value++
  }
}

// 跳转到指定题目
const jumpToQuestion = (module: string, indexInModule: number) => {
  // 直接根据模块和模块内索引计算在排序后数组中的位置
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  let totalCount = 0;
  
  // 找到目标模块在顺序中的位置
  const targetModuleIndex = moduleOrder.indexOf(module);
  
  // 如果目标模块不在标准模块顺序中，则在其他模块中查找
  if (targetModuleIndex === -1) {
    // 计算标准模块的总题目数
    for (let i = 0; i < moduleOrder.length; i++) {
      if (groupedQuestions.value[moduleOrder[i]]) {
        totalCount += groupedQuestions.value[moduleOrder[i]].length;
      }
    }
    // 在其他模块中查找目标模块
    const otherModules = Object.keys(groupedQuestions.value).filter(m => !moduleOrder.includes(m));
    const targetOtherModuleIndex = otherModules.indexOf(module);
    if (targetOtherModuleIndex !== -1) {
      for (let i = 0; i < targetOtherModuleIndex; i++) {
        totalCount += groupedQuestions.value[otherModules[i]].length;
      }
    }
  } else {
    // 计算目标模块之前所有模块的题目数量
    for (let i = 0; i < targetModuleIndex; i++) {
      const prevModule = moduleOrder[i];
      if (groupedQuestions.value[prevModule]) {
        totalCount += groupedQuestions.value[prevModule].length;
      }
    }
  }
  
  // 计算最终索引：之前模块的题目总数 + 当前模块内的索引
  const index = totalCount + indexInModule;
  if (index >= 0 && index < getSortedQuestions.value.length) {
    currentQuestionIndex.value = index;
  }
}

// 获取当前题目的连续编号
const getCurrentQuestionContinuousNumber = () => {
  if (!currentQuestion.value) return 0;
  
  // 找到当前题目所在的模块
  const currentModule = currentQuestion.value.module;
  if (!currentModule) return currentQuestionIndex.value + 1;
  
  // 找到当前题目在模块中的索引
  const moduleQuestions = groupedQuestions.value[currentModule];
  if (!moduleQuestions) return currentQuestionIndex.value + 1;
  
  const indexInModule = moduleQuestions.findIndex(q => q.id === currentQuestion.value.id);
  if (indexInModule === -1) return currentQuestionIndex.value + 1;
  
  // 使用已有的函数计算连续编号
  return getContinuousQuestionNumber(currentModule, indexInModule);
};

// 获取连续的题目编号
const getContinuousQuestionNumber = (module: string, indexInModule: number) => {
  // 计算当前模块之前所有模块的题目总数
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  let totalCount = 0;
  
  // 找到当前模块在顺序中的位置
  const currentModuleIndex = moduleOrder.indexOf(module);
  
  // 计算之前所有模块的题目数量
  for (let i = 0; i < currentModuleIndex; i++) {
    const prevModule = moduleOrder[i];
    if (groupedQuestions.value[prevModule]) {
      totalCount += groupedQuestions.value[prevModule].length;
    }
  }
  
  // 加上当前模块内的索引+1（因为索引从0开始）
  return totalCount + indexInModule + 1;
};

// 获取模块显示名称
const getModuleDisplayName = (module: string) => {
  const moduleMap: Record<string, string> = {
    'politics': '政治理论',
    'commonSense': '常识判断',
    'language': '言语理解与表达',
    'quantity': '数量关系',
    'judgment': '判断推理',
    'dataAnalysis': '资料分析'
  };
  
  return moduleMap[module] || module;
};

// 获取当前题目模块
const getCurrentQuestionModule = () => {
  if (!currentQuestion.value || !currentQuestion.value.module) return ''
  
  return getModuleDisplayName(currentQuestion.value.module);
}

// 获取进度条颜色
const getProgressColor = (scoreRate: number) => {
  if (scoreRate >= 80) return '#67c23a';
  if (scoreRate >= 60) return '#e6a23c';
  return '#f56c6c';
};

// 获取性能评价文本
const getPerformanceText = (scoreRate: number) => {
  if (scoreRate >= 90) return '优秀';
  if (scoreRate >= 80) return '良好';
  if (scoreRate >= 60) return '及格';
  return '需加强';
};

// 获取得分率标签类型
const getScoreRateTagType = (scoreRate: number): 'success' | 'warning' | 'danger' => {
  if (scoreRate >= 80) return 'success';
  if (scoreRate >= 60) return 'warning';
  return 'danger';
};

// 组件挂载时获取结果数据
onMounted(() => {
  fetchPaperResult()
})

// 正确题数 - 优先使用计算结果，否则重新计算
const correctCount = computed(() => {
  // 如果有计算结果，优先使用
  if (calculatedCorrectCount.value > 0) {
    return calculatedCorrectCount.value;
  }
  
  // 否则重新计算
  return paperQuestions.value.filter(question => {
    // 使用模块+ID作为键获取用户答案
    const userAnswer = userAnswers.value[`${question.module}-${question.id}`]
    if (!userAnswer) return false
    
    if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
      return userAnswer === question.correctAnswer
    } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
      // 多选题答案比较
      const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : []
      const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : []
      return JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort())
    }
    return true // 填空题、简答题等暂不判断
  }).length
})

// 错误题数 - 优先使用计算结果，否则重新计算
const wrongCount = computed(() => {
  // 如果有计算结果，优先使用
  if (calculatedWrongCount.value > 0) {
    return calculatedWrongCount.value;
  }
  
  // 否则重新计算
  return paperQuestions.value.filter(question => {
    // 使用模块+ID作为键获取用户答案
    const userAnswer = userAnswers.value[`${question.module}-${question.id}`]
    if (!userAnswer) return false
    
    if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
      return userAnswer !== question.correctAnswer
    } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
      // 多选题答案比较
      const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : []
      const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : []
      return JSON.stringify(userAnswersArray.sort()) !== JSON.stringify(correctAnswersArray.sort())
    }
    return false // 填空题、简答题等暂不判断
  }).length
})

// 总题数
const totalQuestions = computed(() => {
  return paperQuestions.value.length
})

// 得分百分比
const scorePercentage = computed(() => {
  // 如果totalScore为0，返回0避免除以0错误
  if (totalScore.value === 0) return 0;
  // 使用后端返回的得分计算百分比，确保与圆圈中显示的分数一致
  return Math.round((userScore.value / totalScore.value) * 100);
});

// 得分颜色
const scoreColor = computed(() => {
  if (scorePercentage.value >= 80) return '#67c23a'
  if (scorePercentage.value >= 60) return '#e6a23c'
  return '#f56c6c'
})

// 过滤后的题目
const filteredQuestions = computed(() => {
  // 首先按照模块顺序对题目进行排序
  const moduleOrder = ['politics', 'commonSense', 'language', 'quantity', 'judgment', 'dataAnalysis'];
  
  // 创建一个排序后的题目数组
  const sortedQuestions = [...paperQuestions.value].sort((a, b) => {
    const moduleA = a.module || '';
    const moduleB = b.module || '';
    const moduleAIndex = moduleOrder.indexOf(moduleA);
    const moduleBIndex = moduleOrder.indexOf(moduleB);
    
    // 如果两个题目都在模块顺序列表中，按照模块顺序排序
    if (moduleAIndex !== -1 && moduleBIndex !== -1) {
      if (moduleAIndex !== moduleBIndex) {
        return moduleAIndex - moduleBIndex;
      }
      // 如果在同一模块中，保持原有顺序
      return 0;
    }
    
    // 如果只有A在模块顺序列表中，A排在前面
    if (moduleAIndex !== -1) {
      return -1;
    }
    
    // 如果只有B在模块顺序列表中，B排在前面
    if (moduleBIndex !== -1) {
      return 1;
    }
    
    // 如果都不在模块顺序列表中，保持原有顺序
    return 0;
  });
  
  if (analysisFilter.value === 'all') return sortedQuestions;
  
  return sortedQuestions.filter(question => {
    // 使用模块+ID作为键获取用户答案
    const userAnswer = userAnswers.value[`${question.module}-${question.id}`];
    
    switch (analysisFilter.value) {
      case 'wrong':
        if (!userAnswer) return false;
        if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
          return userAnswer !== question.correctAnswer;
        } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
          const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : [];
          const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : [];
          return JSON.stringify(userAnswersArray.sort()) !== JSON.stringify(correctAnswersArray.sort());
        }
        return false;
      case 'correct':
        if (!userAnswer) return false;
        if (question.type === 'single' || question.type === 'single_choice' || question.type === 'trueFalse' || question.type === 'true_false') {
          return userAnswer === question.correctAnswer;
        } else if (question.type === 'multiple' || question.type === 'multiple_choice') {
          const userAnswersArray = Array.isArray(userAnswer) ? userAnswer : [];
          const correctAnswersArray = Array.isArray(question.correctAnswers) ? question.correctAnswers : [];
          return JSON.stringify(userAnswersArray.sort()) === JSON.stringify(correctAnswersArray.sort());
        }
        return true;
      case 'unanswered':
        return !userAnswer;
      default:
        return true;
    }
  });
});

// 清理题目内容HTML，防止XSS攻击并处理图片大小
const sanitizeQuestionHtml = (html: string) => {
  if (!html) return '';
  // 使用htmlUtils中的modifyQuestionContentImageSizeInHTML函数处理题目内容HTML
  return modifyQuestionContentImageSizeInHTML(html);
};

// 清理选项内容HTML，防止XSS攻击并处理图片大小
const sanitizeOptionHtml = (html: string) => {
  if (!html) return '';
  // 使用htmlUtils中的modifyOptionImageSizeInHTML函数处理选项内容HTML
  return modifyOptionImageSizeInHTML(html);
};

</script>

<style scoped>
.paper-test-result {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.result-overview {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}

.result-overview :deep(.el-card__body) {
  padding: 20px;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid rgba(255, 255, 255, 0.3);
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: white;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

.subtitle {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 4px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

/* 成绩展示区 */
.score-banner {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
}

.score-main {
  display: flex;
  gap: 30px;
  align-items: center;
  flex: 1;
}

.score-circle {
  position: relative;
  width: 140px;
  height: 140px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: white;
  border-radius: 50%;
  padding: 8px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
}

:deep(.score-circle .el-progress__text) {
  display: none !important;
}

.score-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  z-index: 10;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.score {
  display: block;
  font-size: 32px;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.total {
  font-size: 16px;
  color: #999;
  line-height: 1.2;
  margin-top: 4px;
}

/* 得分信息展示 */
.score-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex: 1;
}

/* 计分方式展示 */
.scoring-method-display {
  background: rgba(255, 255, 255, 0.2);
  padding: 10px 14px;
  border-radius: 10px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s;
}

.scoring-method-display:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateX(5px);
}

.scoring-method-label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 5px;
  font-weight: 500;
}

.scoring-method-label .el-icon {
  font-size: 13px;
}

.scoring-method-value {
  font-size: 13px;
  font-weight: 600;
  color: white;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
  line-height: 1.4;
}

.total-score-display,
.user-score-display,
.score-rate-display {
  background: rgba(255, 255, 255, 0.15);
  padding: 12px 16px;
  border-radius: 10px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s;
}

.total-score-display:hover,
.user-score-display:hover,
.score-rate-display:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateX(5px);
}

.total-score-label,
.user-score-label,
.score-rate-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 6px;
  font-weight: 500;
}

.total-score-value,
.user-score-value,
.score-rate-value {
  font-size: 26px;
  font-weight: bold;
  color: white;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

.score-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  flex: 1;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 8px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s;
}

.detail-item:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-2px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
}

.detail-icon {
  font-size: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  flex-shrink: 0;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 3px;
  flex: 1;
}

.label {
  color: rgba(255, 255, 255, 0.9);
  font-size: 12px;
  font-weight: 500;
}

.value {
  font-weight: bold;
  color: white;
  font-size: 16px;
}

.correct-value {
  color: #a0ffb8;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.wrong-value {
  color: #ffb8b8;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 详细得分信息样式 */
.detailed-score-section {
  margin-top: 30px;
  padding-top: 20px;
}

.section-title {
  font-weight: bold;
  color: #303133;
  font-size: 20px;
  padding: 0 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.section-title.expandable {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #409eff;
  background: none;
  -webkit-text-fill-color: #409eff;
  transition: all 0.3s;
  user-select: none;
}

.section-title.expandable:hover {
  opacity: 0.8;
  transform: translateX(3px);
}

.section-title.expandable .el-icon {
  font-size: 18px;
  transition: transform 0.3s;
  color: #409eff;
}

.section-title.expandable .rotate-icon {
  transform: rotate(90deg);
}

.expand-hint {
  font-size: 13px;
  color: #909399;
  font-weight: normal;
  margin-left: 5px;
}

.detailed-content {
  overflow: hidden;
}

.table-wrapper {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.table-wrapper :deep(.el-table) {
  border-radius: 8px;
}

.table-wrapper :deep(.el-table th) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.table-wrapper :deep(.el-table td) {
  padding: 12px 0;
}

.table-wrapper :deep(.el-progress) {
  width: 100%;
  padding: 0 10px;
}

/* 总体统计卡片 */
.overall-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 25px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  background: white;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  font-size: 32px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.total-score-stat .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.accuracy-stat .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.correct-stat .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.wrong-stat .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.question-analysis {
  margin-bottom: 20px;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.questions-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-item {
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

.question-item.correct {
  border-color: #67c23a;
  background-color: #f0f9eb;
}

.question-item.wrong {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.question-item.unanswered {
  border-color: #909399;
  background-color: #f4f4f5;
}

.question-header {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdfe6;
}

.question-number {
  font-weight: bold;
  color: #409eff;
}

.question-type {
  font-size: 12px;
  color: #409eff;
  background-color: #ecf5ff;
  padding: 2px 8px;
  border-radius: 4px;
}

.question-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.question-status.correct {
  color: #67c23a;
  background-color: #f0f9eb;
  border: 1px solid #67c23a;
}

.question-status.wrong {
  color: #f56c6c;
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
}

.question-status.unanswered {
  color: #909399;
  background-color: #f4f4f5;
  border: 1px solid #909399;
}

.question-content h4 {
  margin: 0 0 15px 0;
  line-height: 1.6;
}

.options-area, .true-false-area {
  display: flex;
  flex-direction: column;
  gap: 8px; /* 减小选项间距 */
  margin-bottom: 15px;
}



/* 用户答案和正确答案区域样式 */
.answer-section {
  margin: 20px 0;
}

.answer-card {
  display: flex;
  align-items: center;
  gap: 0;
  padding: 16px 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 2px solid #e8edf3;
  transition: all 0.3s;
}

.answer-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.answer-item {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  padding: 0 15px;
}

.answer-item:first-child {
  padding-left: 0;
}

.answer-item:last-child {
  padding-right: 0;
}

.answer-divider {
  width: 2px;
  height: 40px;
  background: linear-gradient(180deg, #e8edf3 0%, #c0c4cc 50%, #e8edf3 100%);
  flex-shrink: 0;
}

.answer-label {
  font-weight: 600;
  font-size: 14px;
  white-space: nowrap;
  flex-shrink: 0;
  padding: 4px 12px;
  border-radius: 6px;
  color: white;
}

.user-answer-item .answer-label {
  background: linear-gradient(135deg, #409eff 0%, #5cadff 100%);
}

.correct-answer-item .answer-label {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.answer-value {
  flex: 1;
  color: #303133;
  font-size: 15px;
  font-weight: 500;
  word-break: break-word;
}

/* 正确答案区域样式 */
.correct-answer-section {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  margin: 15px 0;
  display: block;
  min-width: 120px;
  max-width: 300px;
}

.correct-answer-section .label {
  font-weight: bold;
  color: #67c23a;
  margin-right: 10px;
}

/* 填空题/简答题的用户答案样式 */
.user-answer {
  margin-top: 15px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #e8f4fd 0%, #d6ebfa 100%);
  border: 2px solid #409eff;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
}

.user-answer .label {
  font-weight: 600;
  color: #409eff;
  margin-right: 10px;
  font-size: 14px;
}

/* 填空题/简答题的正确答案样式 */
.correct-answer {
  margin-top: 10px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%);
  border: 2px solid #67c23a;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(103, 194, 58, 0.1);
}

.correct-answer .label {
  font-weight: bold;
  color: #67c23a;
  margin-right: 10px;
}

.correct-answer-content {
  font-weight: bold;
  color: #67c23a;
}

.question-analysis-content h5 {
  margin: 15px 0 10px 0;
  color: #409eff;
}

/* 新增主内容区样式 */
.main-content {
  display: flex;
  width: 100%;
  max-width: 1200px;
  gap: 20px;
  margin-bottom: 20px;
  align-items: flex-start;
  overflow: visible;
  height: 600px; /* 设置固定高度以确保左右区域等高 */
  max-height: 600px; /* 设置最大高度 */
}

/* 调整题目区域样式 */
.question-area {
  flex: 3;
  margin-bottom: 0;
  max-width: calc(100% - 220px);
  display: flex;
  flex-direction: column;
  height: 100%; /* 设置为100%以填充容器高度 */
  max-height: none;
  overflow-y: auto; /* 为题目区域添加滚动条 */
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.question-area:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.question-area :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 20px;
  border-bottom: none;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.question-header span {
  font-size: 16px;
  font-weight: 600;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.question-content {
  padding: 25px;
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow-y: visible;
  background: #fafbfc;
}

.question-navigation-bottom {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 25px;
  padding: 20px 25px;
  background: white;
  border-radius: 0 0 12px 12px;
  border-top: 2px solid #e8edf3;
}

.navigation-buttons {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.question-main {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  height: auto;
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.question-title-container {
  flex: 1;
  overflow-y: visible;
  padding: 0 0 15px 0;
  border-bottom: 2px solid #e8edf3;
  margin-bottom: 20px;
}

.question-title {
  margin: 0 0 10px 0;
  font-size: 17px;
  line-height: 1.8;
  display: block;
  width: 100%;
  color: #303133;
  font-weight: 500;
}

.question-title img {
  max-width: 700px;
  max-height: 500px;
  height: auto;
  width: auto;
  object-fit: contain;
}

.options-container {
  flex: 2;
  overflow-y: visible;
  padding: 10px 0;
}

.options-area {
  display: block;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 8px; /* 减小选项间距 */
  text-align: left !important;
  align-items: flex-start;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 0;
  height: auto; /* 确保高度自适应 */
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
  border-radius: 8px;
  transition: all 0.3s;
  border: 2px solid #e8edf3;
  text-align: left !important;
  justify-content: flex-start !important;
  width: 100%;
  max-width: 800px;
  box-sizing: border-box;
  margin: 0;
  margin-right: 0 !important;
  align-self: flex-start;
  min-height: auto;
  height: auto;
  background: white;
}

.option-item:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  transform: translateX(3px);
}

/* 正确选项的绿色样式 */
.option-item.correct-option {
  border: 2px solid #67c23a !important;
  background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%) !important;
}

.option-item.correct-option .option-label {
  color: #67c23a;
}

/* 用户选择且错误的选项样式 */
.option-item.user-selected.user-wrong {
  border: 2px solid #f56c6c !important;
  background: linear-gradient(135deg, #fef0f0 0%, #fde2e2 100%) !important;
}

.option-item.user-selected.user-wrong .option-label {
  color: #f56c6c;
}

.option-label {
  font-weight: 600;
  margin-right: 12px;
  min-width: 24px;
  flex-shrink: 0;
  color: #606266;
  font-size: 15px;
}

.option-content {
  flex: 1;
  line-height: 1.6;
  text-align: left !important;
  max-width: 100%;
  height: auto;
  overflow: visible;
  color: #303133;
  font-size: 15px;
}

.option-content img {
  max-width: 150px !important; /* 将选项图片调大 */
  max-height: 120px !important; /* 将选项图片调大 */
  height: auto;
  width: auto;
  object-fit: contain;
  display: block;
  margin: 5px 0;
}

/* 更强力的左对齐样式 */
.question-content *,
.options-list *,
.option-item *,
.option-content * {
  text-align: left !important;
  justify-content: flex-start !important;
  align-items: flex-start !important;
}

.true-false-area .options-list {
  flex-direction: row;
  gap: 10px;
  max-width: 800px;
  margin: 0 auto;
  height: auto; /* 确保高度自适应 */
}

.true-false-area .option-item {
  margin-right: 10px;
  max-width: 300px;
  align-items: flex-start; /* 修改为flex-start以适应高度自适应 */
  height: auto; /* 确保高度自适应 */
}

/* 调整答题卡样式 */
.answer-sheet {
  flex: 1;
  min-width: 250px;
  max-width: 320px;
  position: static;
  top: auto;
  right: auto;
  display: flex;
  flex-direction: column;
  height: 600px; /* 设置固定高度 */
  max-height: 600px;
  overflow: visible;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.answer-sheet :deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.answer-sheet:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.answer-sheet :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 20px;
  border-bottom: none;
}

.sheet-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sheet-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.sheet-title .el-icon {
  font-size: 18px;
}

.sheet-legend {
  display: flex;
  gap: 15px;
  font-size: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
}

.legend-dot.correct {
  background-color: #67c23a;
}

.legend-dot.wrong {
  background-color: #f56c6c;
}

.legend-text {
  color: rgba(255, 255, 255, 0.9);
}

.sheet-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 15px 20px 30px 15px; /* 增加右侧padding，让滚动条与内容保持距离 */
}

.sheet-content::-webkit-scrollbar {
  width: 6px;
}

.sheet-content::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 3px;
}

.sheet-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.sheet-content::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}

.module-section {
  background: #f9fafb;
  border-radius: 10px;
  padding: 15px;
  transition: all 0.3s;
}

.module-section:hover {
  background: #f5f7fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.module-section:last-child {
  margin-bottom: 0;
}

.module-name {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
  border-radius: 8px;
  border-left: 3px solid #409eff;
}

.module-name-text {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.module-count {
  font-size: 12px;
  color: #909399;
  background: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: 500;
}

.module-sheet {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 每行展示5个 */
  gap: 8px;
  padding: 5px;
}

.sheet-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 36px; /* 从44px减小到36px */
  border: 2px solid #dcdfe6;
  border-radius: 6px; /* 从8px减小到6px */
  cursor: pointer;
  transition: all 0.3s;
  background-color: white;
  min-width: 36px; /* 从44px减小到36px */
  font-size: 13px; /* 从14px减小到13px */
  font-weight: 600;
  overflow: hidden;
}

.sheet-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 100%);
  opacity: 0;
  transition: opacity 0.3s;
}

.sheet-item:hover::before {
  opacity: 1;
}

.sheet-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.sheet-item-number {
  position: relative;
  z-index: 1;
}

.sheet-item.correct {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: white;
  border-color: #67c23a;
  box-shadow: 0 2px 6px rgba(103, 194, 58, 0.3);
}

.sheet-item.wrong {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  color: white;
  border-color: #f56c6c;
  box-shadow: 0 2px 6px rgba(245, 108, 108, 0.3);
}

.sheet-item.unanswered {
  background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%);
  color: white;
  border-color: #909399;
  box-shadow: 0 2px 6px rgba(144, 147, 153, 0.2);
}

/* 题目解析 */
.question-analysis-content {
  margin-top: 25px;
  padding: 0;
}

.analysis-divider-text {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.analysis-divider-text .el-icon {
  font-size: 18px;
}

.analysis-wrapper {
  display: flex;
  gap: 15px;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf3 100%);
  border-radius: 12px;
  border-left: 4px solid #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  transition: all 0.3s;
  margin-top: 10px;
}

.analysis-wrapper:hover {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateX(2px);
}

.analysis-icon-badge {
  font-size: 32px;
  width: 45px;
  height: 45px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #fff9e6 0%, #ffe9a8 100%);
  border-radius: 50%;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(255, 193, 7, 0.2);
}

.analysis-text {
  flex: 1;
  line-height: 1.8;
  color: #303133;
  font-size: 15px;
}

.question-analysis-content img {
  max-width: 700px;
  max-height: 500px;
  height: auto;
  width: auto;
  object-fit: contain;
  border-radius: 8px;
  margin: 10px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .overview-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-title h2 {
    font-size: 22px;
  }
  
  .score-banner {
    flex-direction: column;
    gap: 20px;
  }
  
  .score-main {
    flex-direction: column;
    align-items: center;
    gap: 25px;
  }
  
  .score-info {
    width: 100%;
  }
  
  .score-details {
    grid-template-columns: 1fr;
  }
  
  .overall-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .main-content {
    flex-direction: column;
  }
  
  .question-area {
    max-width: 100%;
    max-height: none;
  }
  
  .answer-sheet {
    width: 100%;
    margin-top: 20px;
    height: auto;
    max-height: none;
  }
}

@media (max-width: 1200px) {
  .answer-sheet {
    position: static;
    width: 200px;
    max-width: 200px;
    margin: 0;
    height: auto; /* 使用自适应高度 */
    max-height: none; /* 移除最大高度限制 */
  }
  
  .sheet-content {
    grid-template-columns: repeat(10, 1fr);
    gap: 8px;
  }
  
  .sheet-item {
    height: 25px;
    font-size: 12px;
  }
}
</style>